<template>
  <div style="float: left">
    <div class="block" style="width:20%;margin-top:50px;float: left">
       <el-tree
          :data="treeData"
          node-key="id"
          :expand-on-click-node="false"
          :default-expand-all="false"
          :render-content="renderContent">
      </el-tree>
    </div>
    <div style="width:80%;float: left">
      <el-dialog title="子级新增" :visible.sync="dialogTreeFormVisible">
        <el-form :model="form">
          <el-form-item label="楼栋、楼层名称" :label-width="formLabelWidth" prop="buildingName">
            <el-input v-model="form.buildingName" autocomplete="off" style="width:83%"></el-input>
          </el-form-item>
          <!--projectList-->
          <el-form-item label="父节点" :label-width="formLabelWidth" hidden>
            <el-input v-model="form.pid" autocomplete="off" style="width:83%"></el-input>
          </el-form-item>
          <el-form-item label="类型" :label-width="formLabelWidth" prop="status">
            <el-select v-model="form.status" placeholder="请选择类型" style="width:300px">
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.name"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('form')">取 消</el-button>
          <el-button type="primary" @click="submitTree('form')">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="楼栋新增" :visible.sync="dialogFormVisible" width="40%">
        <el-form :model="form" status-icon ref="form">
          <el-form-item label="楼栋名称" :label-width="formLabelWidth" prop="buildingName">
            <el-input v-model="form.buildingName" autocomplete="off" style="width:500px"></el-input>
          </el-form-item>
          <el-form-item label="楼层" :label-width="formLabelWidth" prop="floorNum">
            <el-input-number v-model="form.floorNum" :min="1" :max="20"></el-input-number>
          </el-form-item>
          <el-form-item label="户型/房间" :label-width="formLabelWidth" prop="roomNum">
            <el-input-number v-model="form.roomNum" :min="1" :max="10" ></el-input-number>
          </el-form-item>
          <el-form-item label="户型名称" :label-width="formLabelWidth" prop="apartmentName" v-for="(item, index) in form.roomNum" :key="item">
            <el-input v-model="form.apartmentName[index]" autocomplete="off" style="width:500px"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('form')">取 消</el-button>
          <el-button type="primary" @click="submit('form')">确 定</el-button>
        </div>
      </el-dialog>
      <!--编辑房间号的房间名和切换图纸-->
      <el-dialog title="房间编辑" :visible.sync="dialogUpdateVisible" width="40%">
        <el-form :model="form" status-icon ref="form">
          <el-form-item label="房间名称" :label-width="formLabelWidth" prop="buildingName">
            <el-input v-model="updateForm.buildingName" autocomplete="off" style="width:500px"></el-input>
          </el-form-item>
          <el-form-item label="户型名称" :label-width="formLabelWidth" prop="apartmentId">
           <el-input v-model="updateForm.apartmentName" autocomplete="off" style="width:500px"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetUpdateForm('form')">取 消</el-button>
          <el-button type="primary" @click="updateSubmit('form')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 新增弹出框 -->
      <el-button type="primary" style="margin:10px 30px;float:right; " @click="openAddPage">新增</el-button>
      <!-- 新增弹出框底层 -->
      <el-button type="danger" @click="deleteSelect" style="margin:10px 5px; float:right;">删除选中</el-button>
      <div style="float:left">
        <image-record-left :buildingDataList="buildingDataList" @nowItem='newItem' :nowSelectd="selectIndex" style="margin-top:60px;width: 20%;"/>
      </div>
      <div style="float:left;width: 80%;">
        <div>
          <el-table
            :data="tableData"
            :row-class-name="tableRowClassName"
            @selection-change="handleSelectionChange">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              prop="buildingName"
              label="楼栋名称">
            </el-table-column>
            <el-table-column
              prop="apartmentName"
              label="户型名称">
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              show-overflow-tooltip
              :formatter="formatDate">
            </el-table-column>
            <el-table-column
              label="操作">
              <template slot-scope="scope">
                 <el-button type="text" @click="update(scope.row)">编辑</el-button>
                 <el-button type="text" style="color:red;" @click="deleteSelects(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  var pageParams = { page: { pageSize: 10, pageNo: 1 } }
  import { mapGetters } from 'vuex'
  import {
    getProjectBuildingList,
    getAllProjectBuildingLists,
    addProjectBuilding,
    getAllApartmentList,
    updateProjectBuilding,
    deleteProjectBuilding,
    deleteProjectBuildingByPid,
    getProjectBuildingListTree,
    getBuildingInfoList,
    getRoomInfoList
  } from '@/api/buildings'
  import ImageRecordLeft from '../components/ImageRecordLeft'
  import { formatDate1 } from '@/api/project'

  export default {
    components: {
      ImageRecordLeft
    },
    name: 'index',
    computed: {
      ...mapGetters([
        'currentProject',
        'projects',
        'userInfo'
      ])
    },
    watch: {
      currentProject: function(n, o) {
        console.log('urrent')
        this.getBuildingInfo()
      }
    },
    data() {
      return {
        selectIndex: 0,
        buildingDataList:[],
        statusList: [{ 'name': '楼栋', 'value': 1 }, { 'name': '楼层', 'value': 2 }, { 'name': '房间号', 'value': 3 }],
        treeData: [],
        apartmentList:[],
        page: {
          currentPage: 1,
          pageSize: 10,
          total: 0
        },
        tableData: [],
        /*新增弹出框操作*/
        dialogUpdateVisible:false,
        dialogTableVisible: false,
        dialogFormVisible: false,
        dialogTreeFormVisible: false,
        currentProjectBuildingId:'',
        form: {
          buildingName: '',
          projectId: '',
          apartmentName: [],
          apartmentNum: 0,
          floorNum: 0,
          roomNum: 0
        },
        updateForm: {
          projectBuildingId:'',
          apartmentName:'',
          apartmentId:'',
          buildingName: '',
          projectId: '',
          pid:'',
          companyId:'',
          apartmentNum: 0,
          floorNum: 0,
          roomNum: 0,
          status:''
        },
        formLabelWidth: '120px',
        //////////////////////////
        /*选中删除*/
        multipleSelection: [],
        pidList: [{}]
      }
    },
    methods: {
      //获取楼栋，然后获取第一栋楼的房间信息
      getBuildingInfo(){
        getBuildingInfoList({"projectId":this.currentProject.projectId}).then(res =>{
          this.buildingDataList=res.data;
          if(res.data.length>0){
            this.getRoomInfo(res.data[0].projectBuildingId);
            this.currentProjectBuildingId=res.data[0].projectBuildingId;
          }
        })
      },
      //获取当前楼栋的所有房间信息
      getRoomInfo(pid){
        getRoomInfoList({
          'pageVo': {
              'pageSize': this.page.pageSize,
              'pageNo': this.page.currentPage
            },
          'pid':pid,
          'projectId': this.currentProject.projectId}).then(res =>{
            this.tableData=[];
            this.tableData=res.data.resultList;
            this.page.total=res.data.pageVo.total;
        })
      },
      newItem(data) {
        this.selected = data
        /*楼层房间号获取*/
        this.getRoomInfo(data.projectBuildingId);
        this.currentProjectBuildingId=data.projectBuildingId;
      },
      append(data) {
        this.form.buildingName = '';
        this.form.pid=data.value;
        this.dialogTreeFormVisible = true;

      },
      remove(node, data) {
          const parent = node.parent;
          const children = parent.data.children || parent.data;
          let index = children.findIndex(d => d.value === data.value);
          children.splice(index, 1);
          deleteProjectBuildingByPid({'projectBuildingId':parseInt(data.value),'projectId':this.currentProject.projectId}).then(res =>{
               this.getBuildingInfo()
          }).catch(res =>{
              this.$message.error(res.message);
          });
      },
      renderContent(h, { node, data, store }) {
          return (
              <span class="custom-tree-node">
              <span>{node.label}</span>
              <span>
              <el-button class="el-icon-plus" size="mini" type="text" on-click={ () => this.append(data) }></el-button>
              <el-button class="el-icon-delete" size="mini"  type="text" on-click={ () => this.remove(node, data) }></el-button>
          </span>
          </span>);
      },
      formatDate(row, column) {
        let date = new Date(parseInt(row.createTime))
        return formatDate1(date)
      },
      //新增页面取消按钮
      //新增页面
      openAddPage() {
          this.getProjectBuildingLists()
          this.dialogFormVisible = true
      },
      resetForm(form) {
        this.dialogFormVisible = false
        this.dialogTreeFormVisible = false
      },
      resetUpdateForm(updateForm) {
        this.dialogUpdateVisible = false
      },
      //编辑
      update(row){
          this.updateForm = Object.assign({}, row)
          console.log("update",this.updateForm)
          this.getAllApartmentList();
          this.dialogUpdateVisible = true
      },
      //获取所有户型
      getAllApartmentList(){
        getAllApartmentList({'projectId':this.currentProject.projectId}).then(res=>{
            this.apartmentList = res.data;
        });
      },
      //提交
      submit(form) {
        this.form.projectId = this.currentProject.projectId
        this.form.apartmentNum=this.form.roomNum
        addProjectBuilding(this.form).then(res =>{         
          this.getBuildingInfo();
          this.getProjectBuildingTree();
          this.dialogFormVisible = false
          this.$message.success(res.message)
        }).catch(res => {
          this.$message.error(res.message)
        })
      },
       //提交
      updateSubmit(updateForm) {
        updateProjectBuilding(this.updateForm).then(res =>{         
          this.getRoomInfo(this.currentProjectBuildingId);
          this.getProjectBuildingTree();
          this.dialogUpdateVisible = false
          this.$message.success(res.message)
        }).catch(res => {
          this.$message.error(res.message)
        })
      },
      //删除选中
      deleteSelect(row) {
        deleteProjectBuilding(this.multipleSelection).then(res => {
          this.$message.success(res.message)
          this.getRoomInfo(this.currentProjectBuildingId);
        }).catch(res => {
          this.$message.error(res.message)
        })
      },
      //删除按钮
      deleteSelects(row) {
        deleteProjectBuilding([row]).then(res => {
          this.$message.success(res.message)
          this.getRoomInfo(this.currentProjectBuildingId);
        }).catch(res => {
          this.$message.error(res.message)
        })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      getProjectBuildingLists() {
        getAllProjectBuildingLists({
          'companyId': this.userInfo.companyId,
          'projectId': this.currentProject.projectId
        }).then(res => {
          this.pidList = res.data
        }).catch(res => {

        })
      },
      tableRowClassName({ row, rowIndex }) {
        if (rowIndex === 1) {
          return 'warning-row'
        } else if (rowIndex === 3) {
          return 'success-row'
        }
        return ''
      },
      handleSizeChange(val) {
        this.page.pageSize = val
        this.getRoomInfo(this.currentProjectBuildingId);
        console.log(`每页 ${val} 条`)
      },
      handleCurrentChange(val) {
        this.page.currentPage = val
        this.getRoomInfo(this.currentProjectBuildingId);
        console.log(`当前页: ${val}`)
      },
      //提交
      submitTree(form) {
        this.form.projectId = this.currentProject.projectId
        addProjectBuilding(this.form).then(res => {
          if (res.data != null) {
            let newChild = {}
            newChild = { id: res.data.projectBuildingId, label: this.form.buildingName, children: [] }
            if (!this.treeData.children) {
              this.$set(this.treeData, 'children', [])
            }
            this.getProjectBuildingTree()
             this.getRoomInfo(this.currentProjectBuildingId);
            this.dialogTreeFormVisible = false
            this.$message.success(res.message)
          } else {
            this.$message.error('添加失败')
          }
        }).catch(res => {
          this.$message.error(res.message)
        })
      },
      getProjectBuildingTree() {
        getProjectBuildingListTree({ 'projectId': this.currentProject.projectId }).then(res => {
          this.treeData = res.data
        })
      }
    },
    created() {
      this.getBuildingInfo();
      this.getProjectBuildingTree()
    }
  }
</script>

<style scoped>

</style>
